<template>
  <el-row class="main" justify="center" align="middle">
    <el-col :span="6">
      <el-card>
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="40px"
          class="demo-ruleForm">
          <el-form-item label="帐号" prop="username">
            <el-input v-model="ruleForm.username" type="text" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>

</template>

<script lang="ts" setup>
import { userLogin } from '../api/user'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const store = useStore()
const ruleFormRef = ref<FormInstance>()
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入帐号'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  password: 'ZZ134679',
  username: '周洲'
})

const rules = reactive({
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('验证成功', ruleForm)
      userLogin(ruleForm).then((res) => {
        console.log(res)
        store.commit('user/initUserInfoMut', res.data)
        localStorage.setItem("vue-admin-userinfo", JSON.stringify(res.data)); //本地持久存储用户信息
        router.push({
          path: '/'
        })
      })
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.main {
  height: 100vh;
  background-color: #d8d8d8;
}
</style>